<template>
    <div class="app-login">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="top">
        <el-form-item prop="phone" label="手机号">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="form.password" type="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="isLoading" @click="onSubmit">登录</el-button>
        </el-form-item>
      </el-form>
      <h1>登录</h1>
    </div>
</template>

<script>
// import request from '@/utils/request'
// import qs from 'qs'
// 引入的封装的接口功能组件
import { login } from '@/services/user'
export default {
  name: 'LoginIndex',
  data () {
    return {
      form: {
        phone: '18201288771',
        password: '111111'
      },
      //  用于设置表单校验规则
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '密码长度为6到18位', trigger: 'blur' }
        ]
      },
      isLoading: false
    }
  },
  methods: {
    //  登录功能
    async onSubmit () {
      try {
        await this.$refs.form.validate()
        // 发送网络请求
        this.isLoading = true
        // const { data } = await request({
        //   method: 'POST',
        //   url: '/front/user/login',
        //   // Headers: { 'content-type': 'application/x-www-form-urlencoded'}
        //   data: qs.stringify(this.form)
        // })
        const { data } = await login(this.form)
        this.isLoading = false
        // 处理返回数据
        // console.log(respon)
        if (data.state === 1) {
          this.$message.success(data.message)
          // 将用户信息存储到vuex中
          this.$store.commit('setUser', data.content)
          // 根据可能存储的redirect数据进行跳转
          // this.$router.push({
          //   name: 'home'
          // })
          this.$router.push(this.$route.query.redirect || '/')
        } else {
          this.$message.error(data.message)
        }
      } catch (error) {
        console.log('校验失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped >

.app-login {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;

  h1 {
    position: absolute;
    top: 50px;
  }

  .el-form {
    background-color: #fff;
    width: 300px;
    padding: 20px;
    border-radius: 5px;

    .el-button {
      width: 100%;
    }
  }

}
</style>
